package HelloSeries.ui.prefs.elems.flextables.editor;

import java.awt.Color;
import java.awt.Component;

import javax.swing.AbstractCellEditor;
import javax.swing.JCheckBox;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.TableCellEditor;

public class ConfEditor extends AbstractCellEditor implements TableCellEditor {
	private JTextField textfield;
	private JCheckBox checkbox;
	private JTable table;
	private String content;
	private Boolean checkvalue;
	private Object value;
	private int current_row;

	public ConfEditor() {
		super();
		textfield = new JTextField();
		checkbox = new JCheckBox();
	}

	public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
		this.table = table;
		this.value = value;
		this.current_row = row;
		if(value instanceof Component) {
			textfield = (JTextField) value;
			content = textfield.getText();
			return textfield;
		}
		else if (value instanceof Boolean){
			checkbox.setSelected((Boolean) value);
			checkvalue = isSelected;
			return checkbox;
		}
		return null;
	}

	public Object getCellEditorValue() {
		if(value instanceof Component) {
			content = textfield.getText();
			return content;
		}
		else if (value instanceof Boolean){
			return checkbox.isSelected();
		}
		return null;
	}

	public boolean stopCellEditing() {
		content = textfield.getText();
		if(value instanceof Component) {
			if (content.equals("")) super.cancelCellEditing();
			else if (!isDouble(content) && ( current_row == 0 || current_row == 1)) {
				textfield.setBackground(Color.RED);
				return false;
			}
			else if (!isInteger(content) && ( current_row == 2 || current_row == 3)) {
				textfield.setBackground(Color.RED);
				return false;
			}
		}
		return super.stopCellEditing();
	}

	public boolean isDouble(String s) {
		boolean isValid = true;
		try{ Double.parseDouble(s); }
		catch(NumberFormatException nfe){ isValid = false; }
		return isValid;
	}

	public void raisePopUp(String mess){
		JOptionPane.showMessageDialog(new JOptionPane(),mess,"Erreur",JOptionPane.ERROR_MESSAGE);
	}

	public boolean isInteger(String s) {
		boolean isValid = true;
		try{ Integer.parseInt(s); }
		catch(NumberFormatException nfe){ isValid = false; }
		return isValid;
	}
}